package com.ffyc.ssm.controller;

import com.ffyc.ssm.common.CommonResult;
import com.ffyc.ssm.modle.Admin;
import com.ffyc.ssm.modle.Menu;
import com.ffyc.ssm.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;


@RestController
@RequestMapping(path = "/login")
public class LoginController {

    @Autowired
    LoginService loginService;

    @PostMapping(path = "/login")
    public CommonResult login(Admin admin, HttpSession session){
        CommonResult commonResult = null;
        try {
            Admin admin1 =    loginService.login(admin);
            if (admin1==null){
                commonResult = new CommonResult<Admin>(201,"密码或账号错误" , null);

            }else {
              //  List<Menu> menulist =loginService.menulist(admin1);
                session.setAttribute("admin",admin1);
                commonResult = new CommonResult<Admin>(200,"登录成功" , admin1);
            }
        }catch (Exception e){
            e.printStackTrace();
            commonResult = new CommonResult<Admin>(500,"登录失败" , null);
        }
        return commonResult;
    }
    //根据管理员类型和分配角色 查找菜单
    @GetMapping(path = "/menulist")
    public CommonResult menu(Admin admin){
        CommonResult commonResult = null;
        try {

            List<Menu> menulist =loginService.menulist(admin);
                commonResult = new CommonResult<List<Menu>>(200,"登录成功" , menulist);

        }catch (Exception e){
            e.printStackTrace();
            commonResult = new CommonResult<Admin>(500,"登录失败" , null);
        }
        return commonResult;
    }

    /*退出*/
    @GetMapping(path = "loginOut")
    public void  loginOut(HttpSession session){
        session.invalidate();
    }
}
